

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;


@WebFilter({"/stu", "/student.jsp"})// 过滤器的URL ,使用注解的方式进行配置
public class LoginFilter implements Filter {
    // 实现Filter接口
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 过滤器的具体逻辑
        HttpServletRequest req  = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();

        String username = (String) session.getAttribute("username");

        if(username != null) {
            // 如果用户已登录，则放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            servletRequest.setAttribute("msg", "请先登录！");
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        }
    }
}
